# -*- coding: utf-8 -*-
import pickle
import redis
import logging

logger = logging.getLogger(__name__)


class RedisClient:
    """
    Redis 操作封装类，支持连接、增删查、反序列化等功能。
    """
    def __init__(self, host: str, port: int, password: str, db: int):
        self.host = host
        self.port = port
        self.password = password
        self.db = db
        self.conn = self._connect()

    def _connect(self) -> redis.Redis:
        """
        创建并返回 Redis 连接
        """
        try:
            conn = redis.Redis(host=self.host, port=self.port, password=self.password, db=self.db)
            conn.ping()  # 检查连接是否正常
            logger.info("Redis connection established")
            return conn
        except redis.ConnectionError as e:
            logger.error(f"Redis connection failed: {e}")
            raise

    def get(self, key: str) -> bytes:
        """
        获取指定 key 的值
        """
        return self.conn.get(key)

    def set(self, key: str, value, ex: int = 2600) -> bool:
        """
        设置 key 对应的值，可指定过期时间（秒）
        """
        return self.conn.set(name=key, value=value, ex=ex)

    def delete(self, key: str) -> int:
        """
        删除指定 key
        """
        return self.conn.delete(key)

    def get_object(self, key: str):
        """
        获取并反序列化 key 对应的值
        """
        data = self.get(key)
        return pickle.loads(data) if data else None

    def set_object(self, key: str, obj, ex: int = 2600) -> bool:
        """
        序列化对象并存入 Redis
        """
        try:
            value = pickle.dumps(obj)
            return self.set(key, value, ex)
        except Exception as e:
            logger.error(f"Failed to pickle object: {e}")
            return False
